#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: ct_operate_node02.py 
@version:
@time: 2022/06/08 
"""
from TapClientCore.T07_CaseTemplate.v2.CT03_task.ct_task import CTTask, allure, logger, time, check_wait


# 增删字段
class CTTaskNode02AddDeleteField(CTTask):
    add_or_delete = {}
    name = '自动化-增删字段'
    is_mongodb = False

    # 节点信息更新

    def add_delete_node_update(self, task_name, task_id):
        # 数据处理节点field add delete 节点更新
        time.sleep(check_wait)
        with allure.step(f'获取node schema 并进行{self.name}节点更新'):
            source_node_id = self.TMF_TASK.query_task_by_id(task_id).get('data').get('dag').get('edges')[0].get(
                'source')
            fields = self.get_field_by_node_id(source_node_id)
            field_update = self.add_delete_meta(fields)
        with allure.step('field rename 节点更新'):
            field_add_delete = {
                'operations': field_update
            }
            self.update_task_op_node(task_name, self.name, field_add_delete)

    # 增删字段meta
    def add_delete_meta(self, fields):
        op = self.add_or_delete.get('op')
        from uuid import uuid4
        if op == 'REMOVE':
            for column in fields:
                if column.get('field_name') == self.add_or_delete.get('column'):
                    return [
                        {
                            'field': one.get('field_name'),
                            'field_name': one.get('field_name'),
                            'id': one.get('id'),
                            'label': one.get('filed_name'),
                            'op': op,
                            'operand': True,
                            'primary_key_position': one.get('primary_key_position'),
                            'table_name': 'table',
                            'type': one.get('data_type')
                        } if one.get('primary_key_position') else
                        {
                            'field': one.get('field_name'),
                            'field_name': one.get('field_name'),
                            'id': one.get('id'),
                            'label': one.get('filed_name'),
                            'op': op,
                            'operand': True,
                            'table_name': 'table',
                            'type': one.get('data_type')
                        }
                        for one in [column]
                    ]
            raise Exception('NOT FOUND REMOVE COLUMN')
        elif op == 'CREATE':
            return [
                {
                    'action': 'create_sibling',
                    'data_type': "String",
                    'field': self.add_or_delete.get('column'),
                    'id': str(uuid4()),
                    'label': self.add_or_delete.get('column'),
                    'level': 1,
                    'op': op,
                    'tableName': '',
                    'triggerFieldId': ''
                }
            ]

    def ADD_DELETE_FIELD_NODE(self, data):
        node_config = data.pop('node_config')
        self.add_or_delete = node_config.get('add_delete_field')
        data['task_config']['node'] = node_config
        return data

    # 字段增加删除
    def column_add_delete(self, column_list):
        if self.add_or_delete.get('op') == 'REMOVE':
            column_list = list(column_list)
            column_list.remove(self.add_or_delete.get('column'))
        elif self.add_or_delete.get('op') == 'CREATE':
            if self.is_mongodb:
                ...
            else:
                column_list = [self.add_or_delete.get('column'), *column_list]
        return column_list

    # 数据增加删除
    def data_add_delete(self, data):
        from copy import deepcopy
        copy_data = deepcopy(data)
        new_data = []
        if self.add_or_delete.get('op') == 'REMOVE':
            for one in copy_data:
                if type(one) is tuple:
                    tmp = tuple(one[:-1])
                    new_data.append(tmp)
                else:
                    one.pop('title')
                    new_data.append(one)
        elif self.add_or_delete.get('op') == 'CREATE':
            for one in copy_data:
                if type(one) is tuple:
                    if self.is_mongodb:
                        new_data = copy_data
                    else:
                        tmp = *one, ''
                        new_data.append(tmp)
                else:
                    new_data = copy_data
        return new_data

    # 全量
    def TASK_ADD_DELETE_FIELD_INITIAL(self, parallel_data):
        data = None
        record_id = None
        task_name = None
        # 随机等待
        self.random_wait()
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            operate = data.pop('operate')
            operate_source = operate.get('source')
            source_info = operate_source.get('source_info')
            source_table = operate_source.get('table')
            operate_target = operate.get('target')
            target_info = operate_target.get('target_info')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.ADD_DELETE_FIELD_NODE(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table

            source_where_column = operate_source.get('where')
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            # stats check
            _stats = operate.get('stats_check').get('initial')
            _stats_initial = _stats.get('insert')
            self.drop_target_table(_target)
            with allure.step('创建任务'):
                self.create_data_copy_development(data)
            # initial stats insert 校验
            with allure.step('任务状态等待'):
                self.scheduled_task_wait_it_complete(task_name)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # check
            self.tap_check(
                source_info,
                source_table,
                target_info,
                target_table
            )
            # column check
            self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.column_add_delete
            )
        finally:
            self.release_table(record_id)
            self.generate_task_url(task_name, data.get('task_type'))
            logger.info(self.task_url)
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 增量
    def TASK_ADD_DELETE_FIELD_CDC(self, parallel_data):
        data = None
        # 随机等待
        self.random_wait()
        record_id = None
        source_delete = None
        task_name = None
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')

            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.ADD_DELETE_FIELD_NODE(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            # stats check
            _stats = operate.get('stats_check').get('cdc')
            _stats_initial = _stats.get('initial')
            _stats_insert = _stats.get('insert')
            _stats_update = _stats.get('update')
            _stats_delete = _stats.get('delete')
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                self.create_data_copy_development(data)
            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 增量任务等待时间
            logger.info('等待一段时间')
            time.sleep(180)
            # insert
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # check
            self.tap_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table
            )
            # column check
            self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.column_add_delete
            )
            # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            self.tap_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table
            )
            # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # check
            self.tap_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 全量+增量
    def TASK_ADD_DELETE_FIELD_INITIAL_CDC(self, parallel_data):
        data = None
        source_delete = None
        record_id = None
        _source = None
        _target = None
        task_name = None
        try:
            # 随机等待
            self.random_wait()
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')
            # connector
            _source = self.init_connector(source_info)
            _target = self.init_connector(target_info)
            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            task_name = data.get('task_config').get('config').get('name')

            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            data = self.ADD_DELETE_FIELD_NODE(data)

            # stats check
            _stats = operate.get('stats_check').get('initial+cdc')
            _stats_initial = _stats.get('initial')
            _stats_insert = _stats.get('insert')
            _stats_update = _stats.get('update')
            _stats_delete = _stats.get('delete')
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                self.create_data_copy_development(data)
            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 全量阶段校验
            logger.info('initial check')
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # check
            self.tap_check(
                source_info,
                source_table,
                target_info,
                target_table
            )
            # column check
            self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.column_add_delete
            )
            # 增量阶段校验
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # check
            self.tap_check(
                source_info,
                source_table,
                target_info,
                target_table
            )  # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            self.tap_check(
                source_info,
                source_table,
                target_info,
                target_table
            )  # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # check
            self.tap_check(
                source_info,
                source_table,
                target_info,
                target_table
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 全量 增删字段
    def TASK_ADD_DELETE_FIELD_INITIAL_CHANGE(self, parallel_data):
        data = None
        record_id = None
        task_name = None
        # 随机等待
        self.random_wait()
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            operate = data.pop('operate')
            operate_source = operate.get('source')
            source_info = operate_source.get('source_info')
            source_table = operate_source.get('table')
            operate_target = operate.get('target')
            target_info = operate_target.get('target_info')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.ADD_DELETE_FIELD_NODE(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
                if _target.database_type == 'mongodb':
                    self.is_mongodb = True
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table

            source_where_column = operate_source.get('where')
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            # stats check
            _stats = operate.get('stats_check').get('initial')
            _stats_initial = _stats.get('insert')
            self.drop_target_table(_target)
            with allure.step('创建任务'):
                task_id = self.create_data_copy_development(data).get('id')

            self.add_delete_node_update(task_name, task_id)

            # initial stats insert 校验
            with allure.step('任务状态等待'):
                self.scheduled_task_wait_it_complete(task_name)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # check
            self.tap_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.data_add_delete,
            )
            # column check
            self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.column_add_delete
            )
        finally:
            self.release_table(record_id)
            self.generate_task_url(task_name, data.get('task_type'))
            logger.info(self.task_url)
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 增量 增删字段
    def TASK_ADD_DELETE_FIELD_CDC_CHANGE(self, parallel_data):
        data = None
        # 随机等待
        self.random_wait()
        record_id = None
        source_delete = None
        task_name = None
        try:
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')

            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            with allure.step('任务名获取'):
                task_name = data.get('task_config').get('config').get('name')

            data = self.ADD_DELETE_FIELD_NODE(data)

            # connector
            with allure.step('源数据库初始化'):
                _source = self.init_connector(source_info)
            with allure.step('目标数据库初始化'):
                _target = self.init_connector(target_info)
            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            # stats check
            _stats = operate.get('stats_check').get('cdc')
            _stats_initial = _stats.get('initial')
            _stats_insert = _stats.get('insert')
            _stats_update = _stats.get('update')
            _stats_delete = _stats.get('delete')
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                task_id = self.create_data_copy_development(data).get('id')

            self.add_delete_node_update(task_name, task_id)
            # start
            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 增量任务等待时间
            logger.info('等待一段时间')
            time.sleep(180)
            # insert
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # check
            self.tap_node_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.data_add_delete
            )
            # column check
            self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.column_add_delete
            )
            # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            self.tap_node_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.data_add_delete
            )
            # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # check
            self.tap_node_cdc_check(
                source_info,
                source_table,
                source_where_column,
                target_info,
                target_table,
                self.data_add_delete
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass

    # 全量+增量 增删字段
    def TASK_ADD_DELETE_FIELD_INITIAL_CDC_CHANGE(self, parallel_data):
        data = None
        source_delete = None
        record_id = None
        _source = None
        _target = None
        task_name = None
        try:
            # 随机等待
            self.random_wait()
            # 并行案例初始化
            with allure.step('获取可用表'):
                data = self.lock_and_get_table(parallel_data)
            record_id = data.get('id')

            # operate info
            operate = data.pop('operate')
            operate_source = operate.get('source')
            operate_target = operate.get('target')
            source_info = operate_source.get('source_info')
            target_info = operate_target.get('target_info')
            # connector
            _source = self.init_connector(source_info)
            _target = self.init_connector(target_info)
            # ddl and dml
            source_table = operate_source.get('table')
            source_insert_column = operate_source.get('insert')
            source_update_column = operate_source.get('update')
            source_where_column = operate_source.get('where')
            target_table = operate_target.get('table')

            data['task_config']['config']['name'] += source_table
            task_name = data.get('task_config').get('config').get('name')

            _source.tapclient_connector.CURRENT_TABLE = source_table
            _target.tapclient_connector.CURRENT_TABLE = target_table
            source_insert = _source.tapclient_connector.generate_insert(
                source_insert_column
            )
            source_update = _source.tapclient_connector.generate_update(
                source_update_column,
                source_where_column
            )
            source_delete = _source.tapclient_connector.generate_delete(
                source_where_column
            )

            data = self.ADD_DELETE_FIELD_NODE(data)

            # stats check
            _stats = operate.get('stats_check').get('initial+cdc')
            _stats_initial = _stats.get('initial')
            _stats_insert = _stats.get('insert')
            _stats_update = _stats.get('update')
            _stats_delete = _stats.get('delete')
            # target drop table
            self.drop_target_table(_target)
            with allure.step('执行前删除要插入的数据'):
                _source.tapclient_connector.exec(source_delete)
            with allure.step('创建任务'):
                task_id = self.create_data_copy_development(data).get('id')

            self.add_delete_node_update(task_name, task_id)
            # start
            with allure.step('等待任务运行'):
                self.scheduled_task_wait_it_running(task_name)
            # 全量阶段校验
            logger.info('initial check')
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_initial
            )
            # check
            self.tap_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.data_add_delete
            )
            # column check
            self.column_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.column_add_delete
            )
            # 增量阶段校验
            logger.info('cdc insert and check')
            _source.tapclient_connector.exec(source_insert)
            self.func_wait(
                self.get_task_stats_insert,
                self.get_task_status,
                task_name,
                _stats_insert
            )
            # check
            self.tap_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.data_add_delete
            )
            # update
            _source.tapclient_connector.exec(source_update)
            self.func_wait(
                self.get_task_stats_update,
                self.get_task_status,
                task_name,
                _stats_update
            )
            # check
            self.tap_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.data_add_delete
            )
            # delete
            _source.tapclient_connector.exec(source_delete)
            self.func_wait(
                self.get_task_stats_delete,
                self.get_task_status,
                task_name,
                _stats_delete
            )
            # check
            self.tap_node_check(
                source_info,
                source_table,
                target_info,
                target_table,
                self.data_add_delete
            )
        except Exception as e:
            self.release_table(record_id)
            logger.info(e)
            _source.tapclient_connector.exec(source_delete)
            assert False
        finally:
            self.release_table(record_id)
            if self.task_is_running(task_name):
                self.stop_task_wait_it_paused(task_name)
            self.generate_task_url(task_name, data.get('task_type'))
            try:
                _source.tapclient_connector.close()
                _target.tapclient_connector.close()
            except Exception as e:
                pass
